﻿using System;
using System.Collections.Generic;

namespace winS.Unity
{
    internal class ModuleManager
    {
        private readonly List<Module> moduleList = new List<Module>();
        private readonly Dictionary<Type, int> moduleCacheDictionary = new Dictionary<Type, int>();

        public T GetModule<T>() where T : Module
        {
            if (moduleCacheDictionary.TryGetValue(typeof(T), out int index)) return moduleList[index] as T;

            for (int i = 0; i < moduleList.Count; i++)
            {
                if (moduleList[i] is not T) continue;
                moduleCacheDictionary.Add(typeof(T), i);
                return moduleList[i] as T;
            }
            return null;
        }

        internal void AddModule<T>(T module) where T : Module
        {
            moduleList.Add(module);
        }

        internal void EnsureCapacity(int capacity)
        {
            moduleList.Capacity = capacity;
            moduleCacheDictionary.EnsureCapacity(capacity);
        }
    }
}